<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addfn(id)">{{ isshow ? "修改" : "添加" }}</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="bj(index)">编辑</button>
          </td>
        </tr>
        <tr v-if="list.length == 0">
          <td colspan="5">
            <span class="none">暂无数据</span>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  name: "DEV",
  data() {
    return {
      uname: "",
      age: "",
      gender: "",
      isshow: false,
      id: "",
      list:JSON.parse(localStorage.getItem("list"))
    };
  },
  methods: {
    // 添加数据部分
    addfn(val) {
      if (this.isshow) {
        this.list.splice(val, 1, {
          uname: this.uname,
          age: this.age,
          gender: this.gender,
        });
        this.uname = "";
          this.age = "";
          this.gender = "";
        this.isshow = false;
      } else {
        if (this.uname && this.age && this.gender) {
          this.list.push({
            id: new Date(),
            uname: this.uname,
            age: this.age,
            gender: this.gender,
          });
          this.uname = "";
          this.age = "";
          this.gender = "";
        } else {
          alert("请填写完整信息");
        }
      }
    },
    // 删除部
    del(id) {
      this.list = this.list.filter((item) => {
        return item.id !== id;
      });
    },
    bj(index) {
      this.uname = this.list[index].uname;
      this.age = this.list[index].age;
      this.gender = this.list[index].gender;
      this.id = index;
      this.isshow = true;
    },
  },
 watch:{
  list:{
    handler(val){
      localStorage.setItem("list",JSON.stringify((val && val)||[]))
    } ,
    deep:true
  }
 }
};
</script>
<style lang="less">
.none {
  height: 50px;
  line-height: 50px;
  color: #999;
}
</style>
